package org.example.yupao.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.yupao.domain.User;
import org.example.yupao.service.UserService;
import org.example.yupao.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static org.example.yupao.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author rainsXZ
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-08-18 12:40:28
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    public static final String SALT = "zyudsa";
    public static final String avatarurl = "https://pic.code-nav.cn/user_avatar/1716249269226303490/thumbnail/l4qEaMHi-%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202023-05-22%20102938.png";
    @Resource
    private UserMapper userMapper;

    @Override
    public long userRegister(String userAccount, String userPassWord, String checkPassword,String planetCode) {
        if (StringUtils.isAnyBlank(userAccount,userPassWord,checkPassword)) {
            return -1;
        }
        if (userAccount.length() < 4 || userPassWord.length() < 8 || checkPassword.length() < 8 ) {
            return -1;
        }
        String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        Matcher p = Pattern.compile(regEx).matcher(userAccount);
        if (p.find()) {
            return -1;
        }
        if (!userPassWord.equals(checkPassword)) {
            return -1;
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        long count = userMapper.selectCount(queryWrapper);

        if (count > 0) {
            return -1;
        }

        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode",planetCode);
        count = userMapper.selectCount(queryWrapper);

        if (count > 0) {
            return -1;
        }

        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassWord).getBytes());

        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        user.setAvatarUrl(avatarurl);

        boolean result = this.save(user);
        if (!result) {
            return -1;
        }

        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(userAccount,userPassword)) {
            return null;
        }
        if (userAccount.length() < 4 || userPassword.length() < 8) {
            return null;
        }
        String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        Matcher p = Pattern.compile(regEx).matcher(userAccount);
        if (p.find()) {
            return null;
        }

        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",encryptPassword);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            return null;
        }

        User safetyUser  = getsaftyUser(user);

        request.getSession().setAttribute(USER_LOGIN_STATE,safetyUser);

        return safetyUser;
    }

    @Override
    public User getsaftyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User user = new User();
        user.setId(originUser.getId());
        user.setUsername(originUser.getUsername());
        user.setAvatarUrl(originUser.getAvatarUrl());
        user.setGender(originUser.getGender());
        user.setPhone(originUser.getPhone());
        user.setEmail(originUser.getEmail());
        user.setUserStatus(originUser.getUserStatus());
        user.setIsDelete(originUser.getIsDelete());
        user.setUserRole(originUser.getUserRole());
        user.setTags(originUser.getTags());
        return user;
    }

    @Override
    public int userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    @Override
    public List<User> searchUserByTag(List<String> tagList) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        for (String tag : tagList) {
            queryWrapper.like("tags", tag);
        }

        List<User> userList = userMapper.selectList(queryWrapper);

        return userList.stream().map(this::getsaftyUser).collect(Collectors.toList());
    }
    //TODO
    public List<User> searchUserByTag2(List<String> tagList) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> userList = userMapper.selectList(queryWrapper);
        Gson gson = new Gson();

        return userList.stream().filter(user -> {
                String tagStr = user.getTags();
                if (tagStr == null) {
                    return false;
                }

                Set<String> tagSet = (gson.fromJson(tagStr, new TypeToken<Set<String>>() {
                }.getType()));
                tagSet = Optional.ofNullable(tagSet).orElse(new HashSet<>());
                
                for (String tag : tagList) {
                    if (!tagSet.contains(tag)) {
                        return false;
                    }
                }
            return true;
        }).map(this::getsaftyUser).collect(Collectors.toList());
    }
}




